package com.summer.NIO.udpService;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

public class DatagramChannelClient {
	
	private DatagramChannel mClientChannel;
	private ArrayBlockingQueue<Object> mMessageQueue = new ArrayBlockingQueue<Object>(1024);
	private InetSocketAddress mServiceAddress;
	private InetAddress mLocalAddress = InetAddress.getLocalHost();
	private int mPort;
	
	public DatagramChannelClient(int port,String serviceAddress,int servicePort) throws IOException{
		init(port,serviceAddress,servicePort);
	}
	
	private void init(int port,String serviceAddress,int servicePort) throws IOException{
		mPort = port;
		
		mClientChannel = DatagramChannel.open();
		mClientChannel.bind(new InetSocketAddress(mPort));
		mServiceAddress = new InetSocketAddress(serviceAddress, servicePort);
		
	}
	
	protected void messageSend() throws IOException, InterruptedException{
		ByteBuffer receiveBuf = ByteBuffer.allocate(1024);
		int headLength = mLocalAddress.getAddress().length;
		byte[] port = Util.intToByteArray(mPort) ;
		boolean is = true;
		while(true){
			if(is){
			Object msg = mMessageQueue.take();
			
			ByteBuffer sendMsgBuf = ByteBuffer.allocate(headLength +port.length+ msg.toString().getBytes().length);
			sendMsgBuf.clear();
			sendMsgBuf.put(mLocalAddress.getAddress());
			sendMsgBuf.put(port);
			sendMsgBuf.put(msg.toString().getBytes());
			sendMsgBuf.flip();
			
			int bytesSent = mClientChannel.send(sendMsgBuf, mServiceAddress);
			is=false;
			}
			receiveBuf.clear();
			System.out.println("客户等待消息：");
			mClientChannel.receive(receiveBuf);
			receiveBuf.flip();
			byte[] readByte = new byte[receiveBuf.limit()];
			receiveBuf.get(readByte, 0, readByte.length);
			
			String msg = new String(readByte);
			System.out.println("客户收到消息："+msg);
			
			if(msg.contains("A:")){
				String[] str = msg.split(":");
				
				mClientChannel.send(ByteBuffer.wrap("穿透成功！".getBytes()), new InetSocketAddress(str[1],Integer.valueOf(str[2])));
			}
		}
	}
	
	public void sendMsg(String msg){
		mMessageQueue.add(msg);
	}
	
	public static void main(String[] args) throws IOException, InterruptedException {
//		DatagramChannelClient clientChannel = new DatagramChannelClient(9994, "222.244.95.92", 23744);
//		DatagramChannelClient clientChannel = new DatagramChannelClient(9997, "120.77.52.235", 9999);
		DatagramChannelClient clientChannel = new DatagramChannelClient(9997, "127.0.0.1", 9999);
		clientChannel.sendMsg("nihao！");
		clientChannel.messageSend();
	}
}
